package com.zhoulz.homework.chaptor02.node;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

import org.apache.log4j.Logger;

import com.zhoulz.homework.chaptor02.node.Packet.PacketType;

/**
 * 服务器入站handler
 * @author zhoulz
 *
 */
public class PacketServerChannelOutboundHandler extends ChannelOutboundHandlerAdapter {
	Logger log = Logger.getLogger(PacketServerChannelOutboundHandler.class);
	private boolean stop = false;

	@Override
	public void write(ChannelHandlerContext ctx, Object msg,
			ChannelPromise promise) throws Exception {
//		System.out.println("out start: "+ msg);
		ByteBuf buf = (ByteBuf)msg;
		byte type = buf.getByte(0);
		
		ctx.writeAndFlush(msg);
		// 等待文件接收完成，再close
		if(stop && PacketType.FILE_SEND_DONE.getValue() == type){
			log.info("文件接收完成，安全关闭。");
			ctx.close();
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		log.error("出站异常", cause);
		super.exceptionCaught(ctx, cause);
	}

	public void setStop(boolean stop) {
		this.stop = stop;
	}
	
	
}
